<?php
namespace app\index\model;

class Book extends \think\Model
{
    //获取器
    public function getNameAttr()
    {
        return $this->profile['name'];
    }
    //一对一关联模型
    public function categoryName()
    {
        return $this->hasOne('category','id', 'category_id');
    }

    //关联多对一
    public function profile()
    {
        return $this->belongsTo('category',  'category_id','id');
    }

    //取出书库 -- 每个栏目下的8本书
    public static function cate_book_list()
    {
        //1.取出所有的栏目
        $cate_list = (new \app\admin\model\Category())->cate_list();

        $arr = [];
        //2. 遍历栏目 ，每个栏目下取出8本书
        foreach ($cate_list as $k=>$v) {
            $arr[$k][] = $v['id'];
            $arr[$k][] = $v['name'];
            $arr[$k][] = $list = self::where('category_id', $v['id'])->order('id desc')->limit(8)->select();
        }
        return $arr;
    }

    /**
     *  取出当栏目下的所有书籍名称
     * @param int $cate_id
     * @return array
     */
    public static function cate_book_one($cate_id = 1)
    {
        $cate_list = Category::where('id', $cate_id)->find();
        $arr[] = $cate_list['name'];
        $arr[] = self::where('category_id', $cate_list['id'])->order('id desc')->limit(50)->select();
        return $arr;
    }
}